package com.clouddms.filter;

import com.clouddms.service.auth.TokenBlacklistService;
import com.clouddms.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * JWT认证过滤器
 * 拦截请求，解析JWT Token并设置认证信息
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    
    @Autowired
    private TokenBlacklistService tokenBlacklistService;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String authHeader = request.getHeader("Authorization");
        String token = null;
        String username = null;

        // 从Authorization头中提取JWT Token
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            try {
                username = jwtUtil.getUsernameFromToken(token);
            } catch (Exception e) {
                logger.warn("JWT Token解析失败: " + e.getMessage());
            }
        }

        // 如果用户名不为空且当前没有认证信息，则设置认证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            
            if (jwtUtil.validateToken(token)) {
                // 检查Token是否在黑名单中
                try {
                    String tokenId = jwtUtil.getTokenIdFromToken(token);
                    if (tokenId != null && tokenBlacklistService.isTokenBlacklisted(tokenId)) {
                        logger.warn("Token已被撤销: " + tokenId);
                        filterChain.doFilter(request, response);
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Token黑名单检查失败: " + e.getMessage());
                }
                // 从Token中获取用户信息
                Long userId = jwtUtil.getUserIdFromToken(token);
                Set<String> roles = jwtUtil.getRolesFromToken(token);
                
                // 创建权限列表
                List<SimpleGrantedAuthority> authorities = roles.stream()
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                        .collect(Collectors.toList());

                // 创建认证Token
                UsernamePasswordAuthenticationToken authToken = 
                        new UsernamePasswordAuthenticationToken(username, null, authorities);
                
                // 设置请求详情
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 在请求属性中存储用户信息，方便Controller使用
                request.setAttribute("userId", userId);
                request.setAttribute("username", username);
                request.setAttribute("roles", roles);
                
                // 设置认证信息到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        filterChain.doFilter(request, response);
    }
}